<template>
  <div class="login-bg">
    <van-nav-bar
      title="用户登录"
    />
    <br><br><br><br>
    <div>
      <div class="reg">Welcome</div>
    </div>
    <div class="login-form">
      <van-form  colon  label-width="65px" label-align="right" input-align="left">
        <van-field
          class=""
          v-model="loginData.phone_number"
          name=""
          label="手机"
          placeholder="请输入手机号"
          :rules="[{pattern:phoneValidator, message: '手机号格式错误'}]"
          error-message
        />
        <p>
        <van-field
          v-model="loginData.password"
          type="password"
          name="密码"
          label="密码"
          placeholder="请输入密码"
          :rules="[{pattern:passwordValidator, message: '输入6-20个字母、数字、下划线'}]"
          v-show="flag==true"
          clearable
        />
        <div class="login-form-captcha" v-show="flag==true">
          <div class="login-form-captcha-text">
            <van-field v-model="loginData.verify_code" label="验证码" placeholder="请输入验证码" clearable/>
            <div class="login-form-captcha-img" @click="getCaptchaImg">
              <img :src="captchaImg">
            </div>
          </div>
        </div>
        <div v-show="flag==false">
          <van-field
            v-model="loginData.verify_code"
            center
            clearable
            label="验证码"
            placeholder="短信验证码"
          >
            <template #button>
              <span style="color:#151515" v-show="captchaFlag==true" @click="verify">发送验证码</span>
              <!-- <van-button size="small" type="primary" >发送验证码</van-button> -->
              <div v-show="captchaFlag==false">
                <van-count-down :time="time"  :auto-start="false" @finish="finish" ref="countDown">
                  <template #default="timeData">
                    <span class="block">{{ timeData.seconds }}</span>
                  </template>
                </van-count-down>
              </div>
            </template>
          </van-field>
        </div>
      </van-form>
    </div>
    <div class="login-choice">
      <span :class="{active : tag=='p'}" @click="passwordLogin">密码登录</span>
      <span :class="{active : tag=='cap'}" @click="captchaLogin">验证码登录</span>
    </div>
    <div class="login-buttom">
      <van-button round block type="info" @click="Gotologin" @keyup.enter="Gotologin">登录</van-button>
    </div>
    <div class="login-onther">
      <span>忘记密码</span>
      <span @click="$router.push('/register')">立即注册</span>
    </div>
    <van-overlay :show="overlay" @click="overlay = false" />

  </div>
</template>

<script>
import {login ,getCaptcha ,captchaPhone, getInfo} from '@/api/user'
import md5 from 'js-md5'
export default {
  components: {

  },
  props: {

  },
  data() {
    return {
      // 登录接口所需参数
      loginData: {
        phone_number:'',
        password:'',
        verify_code:'',
        verify_code_id:'',
        captchaPhone:'',
        // 用户登录验证码类型
        verify_type:0,
      },
      // 密码框显示
      flag:true,
      // 手机验证码按钮显示/ 隐藏
      captchaFlag:true,
      // 登录选项切换
      tag:'p',
      // 验证码图片
      captchaImg:'',
      // 倒计时
      time:60000,
      //证照层
      overlay:false,
      // 手机号正则
      phoneValidator:/^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/,
      // 密码正则
      passwordValidator:/^(\w){6,20}$/,
      
    }
  },
  // beforeCreate () {
  //   document.querySelector('body').setAttribute('style', 'background:#FFFFFF')
  // },
  // beforeDestroy () {
  //   document.querySelector('body').removeAttribute('style')
  // },
  created(){
    this.getCaptchaImg();
  },
  mounted() {
    // 绑定监听事件
    window.addEventListener("keydown", this.keyDown);
  },
  methods: {
    // 发送验证码
    verify(){
       this.$toast.loading('验证中...');
      captchaPhone(this.loginData.phone_number)
       setTimeout(() => {
          this.$toast.clear();
          this.captchaFlag = false;
          this.$refs.countDown.reset();
          this.$refs.countDown.start();
        }, 300);
    },
    // 倒计时结束
    finish(){
      this.captchaFlag = true
    },
    // (重新)获取验证码图片
    getCaptchaImg(){
      getCaptcha().then(res=> {
        this.captchaImg = res.data.captcha_content
        this.loginData.verify_code_id = res.data.captcha_id       
      })
    },
    // 登录
    Gotologin(){
      if(this.loginData.phone_number && (this.loginData.password || this.loginData.verify_code)){
        if(this.phoneValidator.test(this.loginData.phone_number) && (this.passwordValidator.test(this.loginData.password) || this.loginData.verify_code)){
          login(this.loginData).then(res=> {
            let _id = res.code
            this.overlay = true
            this.$toast.loading('登陆中...');
              setTimeout(() => {
              this.$toast.clear();
              // 满足条件保存相关信息
              if(_id==0) {
                this.$store.dispatch('getToken',res.data.token)
                window.localStorage.setItem('token', res.data.token)
                this.$store.dispatch('getUserInfo');
                this.$toast.loading('登录成功 ...');
                  setTimeout(() => {
                    this.$toast.clear();
                    this.$router.push('/home');
                  },500);
            }
            else if(_id == -2) {
              this.overlay = false;
              this.$dialog.alert({
                title:'登录失败',
                message: res.msg,
              }).then(() => {
                this.getCaptchaImg();
              });
            }
            else if(_id==-1) {
              this.overlay = false
              this.$dialog.alert({
                title:'登录失败',
                message: "账号或密码错误，请重新输入",
              }).then(() => {
                this.getCaptchaImg();
              });
            }
            },2000)
          })
        }
      }
      
    },
    // 回车键 登录
    keyDown(e) {
      // 回车则执行登录方法 enter键的ASCII是13
      if (e.keyCode === 13) {
        this.login(); // 定义的登录方法
      }
    },
    destroyed() {
      // 销毁事件
      window.removeEventListener("keydown", this.keyDown, false);
    },
    getLoginInfo(){
      this.$router.push('/home');
    },
    passwordLogin(){
      this.tag = 'p';
      this.flag = true;
      this.loginData.verify_type = 0;
    },
    captchaLogin(){
      this.tag = 'cap',
      this.flag = false;
      this.loginData.verify_type = 1;
    }
  }
}
</script>

<style lang="less" >
.active {
  color: rgb(255, 0, 0);
}
.login-bg{
  width: 100%;
  height: 100%;
  // background-color: #ffffff;
}
.reg {
  margin: 0px auto;
  margin-bottom: 50px;
  left: 133px;
  top: 153px;
  width: 109px;
  height: 40px;
  color: rgba(98, 166, 235, 100);
  font-size: 28px;
  text-align: left;
  font-family: PingFangSC-regular;
}
.login-form {
  width: 75%;
  margin: 20px auto;
  .login-form-captcha {
    position: relative;
    width: 100%;
    height: 50px;
    // border: 1px solid red;
    .login-form-captcha-text {
      width: 70%;
    }
    .login-form-captcha-img {
      position: absolute;
      right: -5px;
      top: 5px;
      img {
        width: 90px;
        height: 40px;
        // border: 1px solid blue;
      }
      
    }
  }
}
.login-choice {
  margin: 10px auto;
  display: flex;
  justify-content: space-around;
  width: 60%;
}
.login-buttom {
  margin: 35px auto;
  margin-bottom: 18px;
  // display: flex;
  // align-items: center;
  // justify-content: center;
  width:75%;
  // height: 40px;
  // background-color: rgba(94, 168, 242, 100);
  // color: rgba(255, 255, 255, 100);
  // font-size: 14px;
  // text-align: center;
  // font-family: Microsoft Yahei;
}
.login-onther {
  margin: 5px auto;
  display: flex;
  justify-content: space-around;
  width: 100%;
}
.van-cell__value {
    position: relative;
    overflow: hidden;
    color: #969799;
    text-align: right;
    vertical-align: middle;
    word-wrap: break-word;
    // border-bottom: 1px solid rgb(177, 176, 176);
}
 .van-field__body {
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    align-items: center;
    // border-bottom: 2px solid rgb(75, 141, 240);
}
.van-cell {
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    box-sizing: border-box;
    width: 100%;
    padding: 2.66667vw 4.26667vw;
    overflow: hidden;
    color: #323233;
    font-size: 3.73333vw;
    line-height: 6.4vw;
    background-color: #ffffff;
}
.block {
  font-size: 15px;
  margin-right: 15px;
}
</style>
